// 本地片单服务（按用户隔离）。
// 存储结构：localStorage['watchlist_v1_<userKey>'] = JSON.stringify({ items: [...], ts: number })

const PREFIX = 'watchlist_v1_'

function safeGetLS(key) {
  try {
    if (typeof window === 'undefined' || !window.localStorage) return null
    const raw = window.localStorage.getItem(key)
    return raw ? JSON.parse(raw) : null
  } catch {
    return null
  }
}

function safeSetLS(key, value) {
  try {
    if (typeof window === 'undefined' || !window.localStorage) return
    window.localStorage.setItem(key, JSON.stringify(value))
  } catch {
    // ignore
  }
}

function parseJwtUserId(t) {
  try {
    const part = String(t).split('.')[1]
    if (!part) return null
    const base64 = part.replace(/-/g, '+').replace(/_/g, '/')
    const json = decodeURIComponent(atob(base64).split('').map(c => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)).join(''))
    const payload = JSON.parse(json)
    return payload?.user_id ?? null
  } catch {
    return null
  }
}

function getUserKey() {
  // 优先使用登录时保存的用户编号，其次 JWT 的 user_id，最后 guest
  try {
    const code = (typeof window !== 'undefined') ? window.localStorage.getItem('user_code') : null
    if (code && String(code).trim()) return PREFIX + 'code_' + String(code).trim()
    const token = (typeof window !== 'undefined') ? window.localStorage.getItem('token') : null
    const uid = token ? parseJwtUserId(token) : null
    if (uid != null) return PREFIX + 'uid_' + String(uid)
  } catch {
    // ignore
  }
  return PREFIX + 'guest'
}

function normalizeMovie(m) {
  if (!m) return null
  // 仅保存必要字段，避免占用过多存储
  const id = m.movieId ?? m.id
  if (id == null) return null
  return {
    id,
    movieId: id,
    title: m.title || '未知标题',
    poster: m.poster || m.poster_path || '',
    backdrop: m.backdrop || m.backdrop_path || '',
    year: m.year || null,
    genres: m.genres || null,
    overview: m.overview || null,
    addedAt: Date.now(),
  }
}

export const watchlistService = {
  _key() { return getUserKey() },
  _load() {
    const data = safeGetLS(this._key())
    if (!data || !Array.isArray(data.items)) return { items: [], ts: 0 }
    return data
  },
  _save(items) {
    safeSetLS(this._key(), { items: Array.isArray(items) ? items : [], ts: Date.now() })
  },
  list() {
    const data = this._load()
    // 按添加时间倒序
    return [...data.items].sort((a, b) => (b.addedAt || 0) - (a.addedAt || 0))
  },
  has(id) {
    const data = this._load()
    return data.items.some(x => String(x.id) == String(id))
  },
  add(movie) {
    const item = normalizeMovie(movie)
    if (!item) return { ok: false, reason: 'invalid' }
    const data = this._load()
    const idx = data.items.findIndex(x => String(x.id) == String(item.id))
    if (idx >= 0) {
      // 已存在则更新时间
      data.items[idx] = { ...data.items[idx], ...item, addedAt: Date.now() }
    } else {
      data.items.push(item)
    }
    this._save(data.items)
    return { ok: true, item }
  },
  remove(id) {
    const data = this._load()
    const next = data.items.filter(x => String(x.id) != String(id))
    this._save(next)
    return { ok: true }
  },
  clear() {
    this._save([])
  }
}

export default watchlistService
